var link = $("<link>");
link.attr({type: 'text/css', rel: 'stylesheet', href: 'resources/style.css'});
$("head").append( link ); 			


var stylableElem;
$.ajax({

        url: "CSS_resources/all.html",
        context: document.body,
        dataType: "html",
        success: function (data) {
                var res = $(data);
                $("body").append('<div id="hidden_box"></div>')
                $("#hidden_box").append(res).hide();
                var arr = "";
                var i = 0;
                var attributeSelector = $(".row[class~='standard']");
				
                if ($.browser.mozilla) attributeSelector = $(".row[class~='standard'],.row[class~='mozilla']")
                else if ($.browser.webkit) attributeSelector = $(".row[class~='standard'],.row[class~='webkit']")
                
				attributeSelector.each(function(){
							if ($.browser.msie && $(this).find('code').eq(0).html() == "padding") {
								""  // IE seems not like padding attributes :\ 
							}
							
							else {
								arr += '"' + $(this).find('code').eq(0).html() + '":';
							
								if (i == attributeSelector.length - 1) {
									arr += '"' + $(this).find('code').eq(1).html() + '"';
								}
								else {
									arr += '"' + $(this).find('code').eq(1).html() + '",';
								}
							}
						i++;
                });

				
                var styleAttributes = jQuery.parseJSON("{" + arr + "}");
                var code = "";
                var current;

                function init() {
                        $(".stylable").unbind("click")
                        $(".stylable").each(function () {
                                stylableElem = $(this);
                                stylableElem.bind("click", function (event) {
                                        event.stopPropagation();
                                        stylableElem = $(this);
                                        $("#STYeditor_container").remove();
                                        $("body").append("<div id='STYeditor_container'><div id='STYeditor'></div><div class='STYsource_code'></div></div>");
                                        highlightIt($(this));
                                        createEditor($(this));
                                        $.scrollTo( stylableElem, 800,{offset: {top:-5, left:-30} });
                                })
                        });
                }
                init();
				
				
                /*
                 * UTILITY FUNCTIONS
                 */

                function createEditor(elem) {
                        var i = 0;
                        var html = "";
                        var innerHTML = $(elem).html();
                        code = "";
                        var notSetAttributes = new Array();
                        $.each(styleAttributes, function (name, defaultValue) {
                                defaultValue = defaultValue.split("|")[0];
                                var attribute = elem.css(name);
                                if (attribute != defaultValue && attribute != null && attribute != "" && attribute != "0px" && attribute != "0px 0px" && attribute != "rgb(255, 255, 255)" && attribute != "rgba(255, 255, 255, 1)" && attribute != "transparent" && attribute != "auto auto" && attribute != "normal" && attribute != "0") {
                                        i++;
                                        var possibleValues = "";
                                        possibleValues = styleAttributes[name].split("|")
                                        var possibleValuesSelect = ""  //getPossiboleValuesSelect(possibleValues, name);
                                        html += "<div id='row_" + name + "' class='STYrow'><div class='STYlabel'>" + name + " :</div><div class='STYremove_property'><button class='STYremove_proporty' id='property_" + name + "'>X</button></div><div style='float:left'><input class='STYeditor_input' value='" + attribute + "' id='" + name + "' ></input></div>" + possibleValuesSelect + "</div>";
                                        code += name + ":" + attribute + "; <br/>";
                                } else {
                                        notSetAttributes.push(name);
                                }
                        });
                        $(".STYsource_code").html(code);
                        var html_editor = "<div style='text-align:center'>Your element has " + i + " style attributes </div>" + "<div id='STYcontainer' ><form id='simple-form'>" + html + "</form></div>" + "<div class='STYlabel'>Inner html:</div>" + "<div><textarea id='textareaInnerHtml' class='STYtextarea'>" + innerHTML + "</textarea></div>" + "<div >" + "<button class='STYgreen_button ' id='new_attribute_button'>add attribute</button>" + "</div>" + "<div style='margin:10px 0px 30px 150px; display:none' id='select_new_attribute'><select id='attributes_select' style='font-size:15px;'>" + "</select></div>" + "<div style='margin:0px auto;width:240px'>" + "<button class='STYblue_button' id='source_code_button'>Source Code</button>" + "<button class='STYblue_button' id='close_editor_button'>Close</button>" + "</div>";
                        $("#STYeditor").html(html_editor);

                        function createSelect() {
                                var this_html = "<option></option><option>Your own property</option>";
                                $.each(notSetAttributes, function (i, val) {
                                        this_html += "<option >" + val + "</option>";
                                });
                                $("#attributes_select").html(this_html);
                        }
                        createSelect();
						
                        $("#STYeditor_container").draggable({
                                handle: "#STYeditor"
                        });
                        $(".STYbutton_value").each(function () {
                                $(this).bind("click", function () {
                                        var attr = $(this).attr('data-name');
                                        var value = $(this).html();
                                        $('#row_' + attr).find("input .STYeditor_input").val(value);
                                        stylableElem.css(attr, value);
                                        createEditor(stylableElem);
                                });
                        });
                        $(".STYvalues").click(function () {
                                $(this).next().show();
                                $(".STYvalues").hide();
                                $(this).show();
                        });
                        $('#source_code_button').bind("click", function () {
                                $('.STYsource_code').slideToggle('slow');
                        });
                        $('#copy_css').bind("click", function () {
                                $('.STYsource_code').html().execCommand("Copy");
                        });
                        $('#new_attribute_button').bind("click", function () {
                                $('#select_new_attribute').slideToggle('fast');
                                $("#attributes_select").change(function () {
                                        var new_row;
                                        var select = $(this);
                                        $(this).find("option:selected").each(function () {
                                                if ($(this).text() == "Your own property") new_row = "<div style='clear:both' ><div class='STYlabelNewAttribute'><input id='my_own_property_name' style='width:177px;margin-top:-2px'></input>&nbsp;:</div><div><input  id='" + $(this).text() + "_my_own_property_value' style='width:250px'></input></div></div>";
                                                else new_row = "<div style='clear:both'><div class='STYlabelNewAttribute'>" + $(this).text() + " :</div><div><input class='STYeditor_input' id='" + $(this).text() + "' style='width:250px'></input></div></div>";
                                                $("#STYcontainer").append(new_row);
                                                $("#" + $(this).text()).focus();
                                                $('#select_new_attribute').hide();
                                        });
                                });
                                $("#attributes_select").focus();
                        });
                        $('#close_editor_button').bind("click", function () {
                                $("#STYeditor_container").remove();
                        });
                        $("#textareaInnerHtml").bind("change", function () {
                                var str = $("#textareaInnerHtml").val() + "";
                                stylableElem.html(str);
                                init();
                        });
                }

                function highlightIt(elem) {
                        var width = parseInt(elem.css('width').replace("px", "") * 1 + elem.css('padding-left').replace("px", "") * 1 + elem.css('padding-right').replace("px", "") * 1);
                        var height = parseInt(elem.css('height').replace("px", "") * 1 + elem.css('padding-top').replace("px", "") * 1 + elem.css('padding-bottom').replace("px", "") * 1);
						var top=elem.get(0).offsetTop;
						var left=elem.get(0).offsetLeft;
						var winW = window.innerWidth;
 						var winH = window.innerHeight;
						var editor_left=parseInt(width+left+3);
						var editor_top=parseInt(height+top+3);

						if(parseInt(editor_left+15) >= winW)

							$("#STYeditor_container").css({
								left : "20px",
								top : editor_top
							});
						
						else
							$("#STYeditor_container").css({
								left : editor_left,
								top : editor_top
							});
						
						
                        var sty = "background-color:#222; border: dotted 1px #fff; width:" + width + "px; height:" + height + "px; position:absolute; top:" + top + "px; left:" + left + "px; z-index:40000"
                        var indicator = "<div style='" + sty + "' id='indicator'></div>"
                        $("body").append(indicator);
						var expand={top: "-=50px",left: "-=50px",width: "+=100px",height: "+=100px",opacity: "0.1"}
						var compress={top: "+=50px",left: "+=50px",width: "-=100px",height: "-=100px",opacity: "0.8"}
                        $("#indicator").animate(expand).animate(compress).animate(expand).animate(compress);
                        setTimeout(function () {$("#indicator").remove()}, 1200);
                }

                function noDuplicate(arr) {
                        var r = new Array();
                        o: for (var i = 0, n = arr.length; i < n; i++) {
                                for (var x = 0, y = r.length; x < y; x++) {
                                        if (r[x] == arr[i]) {
                                                continue o;
                                        }
                                }
                                r[r.length] = arr[i];
                        }
                        return r;
                }

                function getPossiboleValuesSelect(arr, name) {
                        if (arr.length == 1) return "";
                        var html = "<div class='STYvalues'>+</div><div class='STYvalues_box'>";
                        for (var i = 0; i < arr.length; i++) {
                                var button = "<div data-name='" + name + "' class='STYbutton_value'>" + arr[i] + "</div>";
                                html += button;
                        }
                        return html + "</div>";
                }
				
                /*
                 * LIVE FUNCTIONS
                 */
                $("input").live("change", function () {
                        if ($(this).attr("id") == "my_own_property_name") return "";
                        if ($(this).attr("id").indexOf("_my_own_property_value") != -1) {
                                stylableElem.css($(this).parent().prev().find("input").val(), $(this).val());
                        }
                        stylableElem.css($(this).attr("id"), $(this).val());
                        createEditor(stylableElem);
                });
                $("button.STYremove_proporty").live("click", function () {
                        var name = $(this).attr("id").replace("property_", "");
                        var default_value = styleAttributes[name].split("|")[0]
                        $("#row_" + name).remove();
                        stylableElem.css(name, default_value);
                        createEditor(stylableElem);
                });
        } // end success function
});

